import stepper from '../stepper/stepper.vue';

import {
	debounce,
	delRepeat
} from "@/common/js/util.js";

export default {
	name: 'Goods',
	components: {
		stepper
	},
	props: {
		// 组选项
		options: {
			type: Array,
			default () {
				return []
			}
		},
		// 组信息
		comboInfo: {
			type: Object
		},
		// 控制全部单选
		allRadio: {
			type: Boolean,
			default () {
				return false
			}
		},
		// 穿透，所有需要判断互斥的产品id
		throughAllPid: {
			type: Array,
			default () {
				return []
			}
		},
		// 对应的互斥ids
		mutexIds: {
			type: Array,
			default () {
				return []
			}
		},
		// 图片高度 0 为默认高度
		imgHeight: {
			type: Number,
			default () {
				return 0;
			}
		},
		// 来自加价购
		addBuy: {
			type: Boolean,
			default () {
				return false
			}
		}
	},
	data() {
		return {
			chooseType: 1, // 选择类型 1单选 2步进器
			comboSum: 0, // 已选组内产品的总和
			comboProducts: [], // 组合产品列表
		};
	},
	mounted() {
		this.initData();
	},
	watch: {
		options() {
			this.initData();
		},
		mutexIds(data) {
			const comboProducts = this.comboProducts;
			comboProducts.map(item => {
				if (data.includes(item.productId)) {
					item.mutex = true;
				} else {
					item.mutex = false;
				}
			});
			this.comboProducts = comboProducts;
		}
	},
	methods: {
		// 初始化数据
		initData() {
			const info = this.comboInfo;
			const options = this.options;
			const comboProducts = []; // 产品组们
			let requiredIdx = []; // 必选商品的索引列表
			let chooseType = 1; // 选择类型 1单选 2步进器
			options.map((item, index) => {

				if (item.maxQty > 1) {
					chooseType = 2;
				}

				const defaultFlag = info.isRelevance && info.hasDefault && index === 0; // 默认选中标识

				// 添加新属性
				if (!this.addBuy) { // 不是加价购

					// 此产品在组内对应的互斥产品列表
					const exclusionIds = this.getExclusionIds(item.productId);
					const inventory = item.conKucun >= 0; // 库存判断

					comboProducts.push({
						kucun: item.conKucun >= 0, // 库存
						name: info.isRelevance ? item.productAlias : item.name, // 产品名
						nameAll: info.isRelevance ? item.productName : item.nameAll, // 产品全名
						itemImg: info.isRelevance ? item.imgUrl : item.itemImg, // 产品图片 
						productId: item.productId, // 产品id
						erpCode: info.isRelevance ? item.productCode : item.erpCode, // 产品编码
						oldPrice: info.isRelevance ? item.price : item.oldPrice, // 产品原价
						price: item.price, // 产品价格，这儿指的是加价价格
						selected: info.isRelevance ? false : item.selected, // 是否必选
						conFeatures: info.isRelevance ? '' : item.conFeatures, // 产品特性
						parentOpid: info.isRelevance ? item.parentOpid : '', // 对应的父级产品
						// 以下是新增字段
						comboIdx: info.comboIdx,
						isSelected: false, //(defaultFlag || item.selected) && inventory, // 是否选择
						isNeed: false, //item.selected, //是否必选
						max: info.isRelevance ? 1 : (inventory ? item.maxQty : 0), // 产品最大可选数量
						min: info.isRelevance ? 0 : (inventory ? (item.minQty || 0) : 0), // 产品最小可选数量
						num: 0, //当前选择
						exclusionIds, // 组内互斥产品id列表
						mutex: false // 互斥锁
					});

					// 如果套餐组中的第一个是必选
					if (item.selected && inventory) {
						requiredIdx.push(index);
					}

					if (defaultFlag && inventory) {
						requiredIdx = [0];
					}

				} else { // 是加价购

					comboProducts.push({
						kucun: true, // 库存
						name: item.name, // 产品名
						nameAll: item.alias, // 产品全名
						itemImg: item.pic, // 产品图片 
						productId: item.id, // 产品id
						erpCode: item.code, // 产品编码
						oldPrice: item.originPrice, // 产品原价
						price: item.basePrice, // 产品价格，这儿指的是加价价格
						selected: false, // 是否必选
						conFeatures: item.features, // 产品特性
						parentOpid: '', // 对应的父级产品
						// 以下是新增字段
						comboIdx: 0,
						isSelected: false, // 是否选择
						isNeed: false, //是否必选
						max: 1, // 产品最大可选数量
						min: 0, // 产品最小可选数量
						num: 0, //当前选择
						exclusionIds: [], // 组内互斥产品id列表
						mutex: false // 互斥锁
					});
				}
			});

			this.chooseType = chooseType;
			this.comboProducts = comboProducts;

			requiredIdx.length && requiredIdx.map(idx => {

				// 选择商品 or 点击加号
				if (chooseType === 1) {
					this.onChooseProduct(idx);
				} else {
					this.handleAdd(idx);
				}

			});
		},

		// 获取产品在组内对应的互斥id数组
		getExclusionIds(productId) {
			const options = this.options;
			const exclusionMap = this.$store.state.exclusionMap;
			const throughAllPid = this.throughAllPid;

			let result = [];
			if (throughAllPid.length) {
				const excArr = exclusionMap[`${productId}_2`] || [];
				result = throughAllPid.filter(x => {
					let flag = excArr.some(y => {
						return x === y;
					});
					return flag;
				});

			} else {
				const excArr = exclusionMap[`${productId}_1`] || [];
				result = options.filter(x => {
					let flag = excArr.some(y => {
						return x.productId === y;
					});
					return flag;
				});

				const exclusionIds = [];
				result.map(exclus => {
					exclusionIds.push(exclus.productId);
				});

				result = exclusionIds;
			}

			return result;
		},

		// 选择产品
		onChooseProduct(idx) {
			const info = this.comboInfo; // 组信息
			const comboProducts = this.comboProducts; // 产品组们
			let curSelects = comboProducts[idx]; // 当前点击的选项
			//当前此组合的总数
			let curTotalNum = this.comboProducts.reduce((acc, item) => {
				return acc + item.num;
			}, 0);

			const isCanAdd = curTotalNum < info.maxQty; //是否可以再添加产品

			// 组单选判断
			if (info.maxQty === 1) {
				let isFlag = false; // 是否选中标识
				comboProducts.map((item, index) => {
					if (index === idx && item.isSelected) {
						isFlag = true;
					}

					item.num = 0;
					item.isSelected = false;

					if (index === idx) {
						item.num = isFlag && this.addBuy ? 0 : 1;
						item.isSelected = isFlag && this.addBuy ? false : true;
					}
				});

				this.comboProducts = comboProducts;

				this.addMutex();

				this.$emit("handleOptionSelects", {
					comboProducts: this.comboProducts,
					comboInfo: info,
					optionIdx: idx,
					status: comboProducts[idx].num ? true : false
				});

			} else {

				if (!curSelects.isSelected && !isCanAdd) return;

				curSelects.isSelected = curSelects.isNeed ? true : !curSelects.isSelected;
				curSelects.num = curSelects.isNeed ? curSelects.min : (curSelects.isSelected ? 1 : 0);
				this.$set(this.comboProducts, idx, curSelects);

				this.addMutex();

				this.$emit("handleOptionSelects", {
					comboProducts: this.comboProducts,
					comboInfo: info,
					optionIdx: idx,
					status: curSelects.num ? true : false
				});

			}

			this.comboSum = this.comboProducts.reduce((acc, item) => {
				return acc + item.num;
			}, 0);

		},

		// 添加或解除互斥锁
		addMutex() {
			const comboProducts = this.comboProducts; // 产品组们
			let tempTotalMutexIds = []; // 临时总的互斥锁id列表
			comboProducts.map(item => {
				if (item.isSelected) {
					tempTotalMutexIds = tempTotalMutexIds.concat(item.exclusionIds);
				}
			});

			// 处理互斥事件
			if (this.throughAllPid.length) {
				let totalMutexIds = this.mutexIds.concat(tempTotalMutexIds); // 总的互斥ids
				totalMutexIds = delRepeat(totalMutexIds); // 去重

				let wipeMutexIds = []; // 需要消除的互斥ids
				comboProducts.map(item => {
					if (!item.isSelected && item.exclusionIds.length) {
						wipeMutexIds = wipeMutexIds.concat(item.exclusionIds);
					}
				});

				// 最终互斥ids
				let finishMutexIds = totalMutexIds.filter(x => {
					let flag = !(wipeMutexIds.some(y => {
						return x == y;
					}))
					return flag;
				});

				this.$emit('handleMutexEvent', {
					comboIdx: this.comboInfo.comboIdx,
					mutexIds: finishMutexIds
				});

				return;
			}

			comboProducts.map(item => {
				if (tempTotalMutexIds.includes(item.productId)) {
					item.mutex = true;
				} else {
					item.mutex = false;
				}
			});
			this.comboProducts = comboProducts;

		},

		// 点击了加号 索引
		handleAdd(idx) {
			const comboProducts = this.comboProducts;
			let curSelects = comboProducts[idx]; // 当前点击的选项
			// 当前此组合选择的总数
			let curTotalNum = comboProducts.reduce((acc, item) => {
				return acc + item.num;
			}, 0);

			const isCanAdd = curTotalNum < this.comboInfo.maxQty; //是否可以再添加

			if (!isCanAdd || (curSelects.num >= curSelects.max)) return;

			curSelects.isSelected = true;
			curSelects.num++;
			this.$set(this.comboProducts, idx, curSelects);

			this.$emit("handleOptionSelects", {
				comboProducts: this.comboProducts,
				comboInfo: this.comboInfo,
				optionIdx: idx,
				status: curSelects.num ? true : false
			});

			this.comboSum = this.comboProducts.reduce((acc, item) => {
				return acc + item.num;
			}, 0);
		},

		// 点击了减号 索引
		handleMinus(idx) {
			const comboProducts = this.comboProducts; //所有选项的选择
			let curSelects = comboProducts[idx]; // 当前点击的选项

			if (curSelects.num >= 1 && (!curSelects.isNeed || curSelects.num > curSelects.min)) {
				curSelects.isSelected = curSelects.num > 1;
				curSelects.num--;
				this.$set(this.comboProducts, idx, curSelects);

				this.$emit("handleOptionSelects", {
					comboProducts: this.comboProducts,
					comboInfo: this.comboInfo,
					optionIdx: idx,
					status: curSelects.num ? true : false
				});
			}

			this.comboSum = this.comboProducts.reduce((acc, item) => {
				return acc + item.num;
			}, 0);
		}

	}
};
